<script setup>
import EditContainer from "@/components/AdminConponents/EditContainer.vue";
import {onMounted, ref, watchEffect, computed} from "vue";
import {useRoute, useRouter} from "vue-router";
import {gamePriceEditAPI, gameGetAPI} from "@/api/AdminApi/game.js";
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from "element-plus";
import {formatJsDateTimeToJavaDateTime} from "@/utils/format.js";

const route = useRoute()
const gamePriceInfo = ref({})
const gameName = ref()

const getGamePriceInfo = async (id = route.params.id) => {
  const res = await gameGetAPI(id)
  gamePriceInfo.value = res.data.gamePrice
  gameName.value = res.data.chineseName
}
onMounted(() => getGamePriceInfo())

// 取消按钮
const router = useRouter()
const cancel = () => {
  router.go(-1)
}

const rules = {
  originPrice: [
    { required: true, message: '请输入原始价格', trigger: 'blur' }
  ],
  currentPrice: [
    { required: true, message: '请输入当前价格', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣', trigger: 'blur' },
    { validator: validateDiscount, trigger: 'blur' }
  ]
}
function validateDiscount(rule, value, callback) {
  if (value === '' || (value >= 0 && value <= 100 && Number.isInteger(parseFloat(value)))) {
    callback();
  } else {
    callback(new Error('折扣必须为0到100之间的整数'));
  }
}

// 默认时间
const defaultTime = new Date(2000, 1, 1, 0, 0, 0)

// 计算回显的日期
const discountTimeRange = computed({
  get() {
    if (gamePriceInfo.value.discountStart && gamePriceInfo.value.discountEnd) {
      return [new Date(gamePriceInfo.value.discountStart), new Date(gamePriceInfo.value.discountEnd)];
    }
    return [];
  },
  set(value) {
    if (value.length === 2) {
      gamePriceInfo.value.discountStart = value[0].toISOString();
      gamePriceInfo.value.discountEnd = value[1].toISOString();
    } else {
      gamePriceInfo.value.discountStart = null;
      gamePriceInfo.value.discountEnd = null;
    }
  }
});

const formRef = ref()
// 修改按钮
const edit = async () => {
  await formRef.value.validate()
  // 检验逻辑
  if (gamePriceInfo.value.discount === 0) {
    gamePriceInfo.value.currentPrice = gamePriceInfo.value.originPrice;
    gamePriceInfo.value.discountStart = null;
    gamePriceInfo.value.discountEnd = null;
  } else {
    if (!gamePriceInfo.value.discountStart || !gamePriceInfo.value.discountEnd) {
      ElMessage.error("请设置折扣日期范围");
      return; // 终止继续执行
    }
    const javaDiscountStartDateTime = formatJsDateTimeToJavaDateTime(gamePriceInfo.value.discountStart)
    const javaDiscountEndDateTime = formatJsDateTimeToJavaDateTime(gamePriceInfo.value.discountEnd)
    gamePriceInfo.value.discountStart = javaDiscountStartDateTime
    gamePriceInfo.value.discountEnd = javaDiscountEndDateTime
  }
  const res = await gamePriceEditAPI(gamePriceInfo.value)
  if (res.code === 1) {
    ElMessage.success("更新成功")
    router.go(-1)
  } else {
    ElMessage.error(res.msg)
  }
}

// 监听将当前价格乘以折扣
watchEffect(() => {
  gamePriceInfo.value.currentPrice = (gamePriceInfo.value.originPrice * (1 - gamePriceInfo.value.discount / 100)).toFixed(2);
});
</script>

<template>
  <EditContainer :title="`${gameName}游戏价格编辑`">
    <template #body>
      <el-form ref="formRef" :model="gamePriceInfo" :rules="rules" label-width="auto" style="max-width: 1200px">
        <el-form-item label="原始价格" prop="originPrice">
          <el-input v-model="gamePriceInfo.originPrice"></el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="currentPrice">
          <el-input v-model="gamePriceInfo.currentPrice" disabled></el-input>
        </el-form-item>
        <el-form-item label="折扣(百分比)" prop="discount">
          <span>立减&nbsp;&nbsp;</span><el-input v-model="gamePriceInfo.discount" style="width: 100px;"></el-input>&nbsp;&nbsp;%
        </el-form-item>
        <el-form-item label="折扣开始和结束时间" style="max-width: 600px">
          <el-date-picker
              v-model="discountTimeRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="defaultTime"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footerLeft>
      <el-button class="button" @click="cancel" type="info">取消</el-button>
    </template>
    <template #footerRight>
      <el-button class="button" @click="edit" type="primary">修改</el-button>
    </template>
  </EditContainer>
</template>

<style scoped>

</style>
